import axios from 'axios';
import { baseUrl } from './env';
import queryString from 'query-string';

let http = axios.create({
    baseURL: baseUrl,
    // withCredentials: true,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
    },
    transformRequest: [function (data) {
        let newData = '';
        for (let k in data) {
            if (data.hasOwnProperty(k) === true) {
                newData += encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) + '&';
            }
        }
        return newData;
    }]
});

function apiAxios(method, url, params, response) {
    http({
        method: method,
        url: url,
        data: method === 'POST' || method === 'PUT' ? params : null,
        params: method === 'GET' || method === 'DELETE' ? params : null,
    }).then(function (res) {
        console.log(res.data);
        if(res.status == 200 && (res.data.code == 5001 || res.data.code == 5002 || res.data.code == 5003)){
            alert("登录授权失效,请重新登录");
            if(process.env.NODE_ENV != 'development') {
              //window.location.href = "/";
              //window.location.href="/parents/index.html#/";
            }
        }

        response(res);
    }).catch(function (err) {
        alert("服务器异常,请重新登录");
      if(process.env.NODE_ENV != 'development') {
        //window.location.href="/parents/index.html#/";
      }
        response(err);
    })
}
function getTokenUrl(url){
  //if(process.env.NODE_ENV != 'development'){
      var storage=window.localStorage;
      var accessToken = storage["access_token"];
      if(url.indexOf('?') == -1){
        url = url + '?' + 'access_token='+ accessToken;
      }else{
        url = url + '&' + 'access_token='+ accessToken;
      }
  //}
  if(url.indexOf('?') == -1){
    url = url + '?' + 't='+ new Date().getTime();
  }else{
    url = url + '&'  + 't='+ new Date().getTime();
  }
  // if(url.indexOf('?') == -1){
  //   url = url + '?' + 'is_debug=1';
  // }else{
  //   url = url + '&'  + 'is_debug=1';
  // }
  return url;
}
export default {

    get: function (url, params, response) {
        url = getTokenUrl(url);
        return apiAxios('GET', url, params, response)
    },
    post: function (url, params, response) {
        url = getTokenUrl(url);
        return apiAxios('POST', url, params, response)
    },
    put: function (url, params, response) {
        url = getTokenUrl(url);
        return apiAxios('PUT', url, params, response)
    },
    delete: function (url, params, response) {
        url = getTokenUrl(url);
        return apiAxios('DELETE', url, params, response)
    }
}
